//
//  OAuthViewController.swift
//  Three-SinaWeibo
//
//  Created by 李旭阳 on 15/11/13.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    //定义个webView 属性
    let webView = UIWebView()
    
        //MARK: loadView
    override func loadView() {
        view = webView
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //加载网络请求
        loadOauthPage()
    }
    
    //MARK: 当view 加载完
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    private func setupUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
    //MARK: 监听关闭item
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: 监听
    @objc private func fullAccount(){
        let jsString = "document.getElementById('userId').value = '1074947943@qq.com' , document.getElementById('passwd').value = 'wan962464123';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //MARK: 发送网络请求
    private func loadOauthPage(){
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL:url!)
        
        webView.loadRequest(request)
    }
    
    
}

extension OAuthViewController: UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        //判断url 是否有值
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        //把开头为这个url 的return 掉
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        
        //如果不是redirect_uri开头的直接return
        if !urlString.hasPrefix(redirect_uri){
            return false
        }
        //此时 request 里面一定有想要的url
        guard let query = request.URL?.query else{
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
        UserAccountViewModel().loadAccessToken(code) {(error) ->() in
            if error != nil {
                SVProgressHUD.showInfoWithStatus(AppErrorTip)
                return
            }
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //发出页面切换的通知
                NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "Welcome")
            })
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss()
    }
    


}
